<template>
  <div class="suggestion-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
          <span class="title">改进建议详情</span>
        </div>
      </template>
      
      <div v-if="loading" class="loading">
        <el-skeleton :rows="6" animated />
      </div>
      
      <div v-else-if="suggestionData" class="detail-content">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="3" border>
          <el-descriptions-item label="建议ID">
            {{ suggestionData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="司机ID">
            {{ suggestionData.analysis?.order_rating?.driver_id || 'N/A' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单号">
            {{ suggestionData.analysis?.order_rating?.order?.order_number || 'N/A' }}
          </el-descriptions-item>
          <el-descriptions-item label="建议类型">
            <el-tag :type="getTypeTagType(suggestionData.suggestion_type)">
              {{ getTypeLabel(suggestionData.suggestion_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(suggestionData.priority)">
              {{ getPriorityLabel(suggestionData.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="生成时间">
            {{ formatDate(suggestionData.generated_time) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 原始评价 -->
        <el-card class="comment-card" style="margin-top: 20px;">
          <template #header>
            <span>原始评价</span>
          </template>
          <div class="comment-content">
            <div class="rating-info">
              <el-rate v-model="suggestionData.analysis?.order_rating?.rating" disabled show-score />
            </div>
            <div class="comment-text">
              {{ suggestionData.analysis?.order_rating?.comment || '暂无评价内容' }}
            </div>
          </div>
        </el-card>
        
        <!-- 改进建议 -->
        <el-card class="suggestion-card" style="margin-top: 20px;">
          <template #header>
            <span>改进建议</span>
          </template>
          <div class="suggestion-content">
            <h4>建议内容</h4>
            <p class="suggestion-text">{{ formatSuggestionContent(suggestionData.suggestion_content) }}</p>
            
            <h4>分析依据</h4>
            <p class="reasoning-text">{{ formatSuggestionContent(suggestionData.suggestion_content) }}</p>
            
            <h4>实施步骤</h4>
            <div class="implementation-steps">
              <ol v-if="suggestionData.implementation_steps">
                <li v-for="(step, index) in suggestionData.implementation_steps" :key="index">
                  {{ step }}
                </li>
              </ol>
              <p v-else>暂无具体实施步骤</p>
            </div>
          </div>
        </el-card>
        
        <!-- 相关分析 -->
        <el-card class="analysis-card" style="margin-top: 20px;">
          <template #header>
            <span>相关分析</span>
          </template>
          <div class="analysis-content">
            <div class="analysis-item">
              <h4>情感分析</h4>
              <p><strong>情感标签:</strong> {{ suggestionData.analysis?.sentiment_label || 'N/A' }}</p>
              <p><strong>情感得分:</strong> {{ suggestionData.analysis?.sentiment_score || 'N/A' }}</p>
            </div>
            
            <div class="analysis-item">
              <h4>关键短语</h4>
              <div v-if="suggestionData.analysis?.key_phrases && suggestionData.analysis.key_phrases.length > 0">
                <el-tag 
                  v-for="phrase in suggestionData.analysis.key_phrases" 
                  :key="phrase"
                  style="margin: 2px;"
                  type="info"
                >
                  {{ phrase }}
                </el-tag>
              </div>
              <p v-else>暂无关键短语</p>
            </div>
            
            <div class="analysis-item">
              <h4>改进领域</h4>
              <div v-if="suggestionData.analysis?.improvement_areas && suggestionData.analysis.improvement_areas.length > 0">
                <div 
                  v-for="area in suggestionData.analysis.improvement_areas" 
                  :key="area.area"
                  class="improvement-area"
                >
                  <el-tag 
                    :type="getPriorityType(area.priority)"
                    style="margin: 2px;"
                  >
                    {{ area.area }} ({{ area.priority }})
                  </el-tag>
                  <p class="area-description">{{ area.description }}</p>
                </div>
              </div>
              <p v-else>暂无改进领域</p>
            </div>
          </div>
        </el-card>
      </div>
      
      <div v-else class="no-data">
        <el-empty description="未找到改进建议" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { evaluationAPI } from '@/api/evaluation'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const suggestionData = ref(null)

onMounted(async () => {
  await loadSuggestionDetail()
})

async function loadSuggestionDetail() {
  const suggestionId = route.params.id
  if (!suggestionId) {
    ElMessage.error('缺少建议ID')
    return
  }
  
  loading.value = true
  try {
    console.log('=== 加载建议详情开始 ===')
    console.log('建议ID:', suggestionId)
    
    // 获取所有改进建议
    const response = await evaluationAPI.getImprovementSuggestions()
    console.log('改进建议API响应:', response)
    
    if (response.data && response.data.data) {
      console.log('所有改进建议数量:', response.data.data.length)
      console.log('所有建议ID:', response.data.data.map(item => item.id))
      
      const suggestion = response.data.data.find(item => item.id == suggestionId)
      console.log('找到的建议:', suggestion)
      
      if (suggestion) {
        suggestionData.value = suggestion
        console.log('设置建议数据成功:', suggestionData.value)
        ElMessage.success('加载建议详情成功')
      } else {
        console.error('未找到ID为', suggestionId, '的建议')
        console.log('可用的建议ID:', response.data.data.map(item => item.id))
        ElMessage.error(`未找到ID为 ${suggestionId} 的改进建议`)
      }
    } else {
      console.error('API响应格式错误:', response)
      ElMessage.error('无法获取改进建议数据')
    }
  } catch (error) {
    console.error('加载建议详情失败:', error)
    ElMessage.error('加载建议详情失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

function goBack() {
  router.go(-1)
}

function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

function getTypeTagType(type) {
  const types = {
    '服务态度': 'primary',
    '驾驶技术': 'success',
    '车辆状况': 'warning',
    '沟通能力': 'info',
    '时间观念': 'danger'
  }
  return types[type] || 'default'
}

function getPriorityTagType(priority) {
  const types = {
    1: 'danger',
    2: 'warning',
    3: 'info'
  }
  return types[priority] || 'default'
}

function getTypeLabel(type) {
  return type || '未知类型'
}

function getPriorityLabel(priority) {
  const labels = {
    1: '高',
    2: '中',
    3: '低'
  }
  return labels[priority] || priority
}

function getPriorityType(priority) {
  const types = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return types[priority] || 'info'
}

function formatSuggestionContent(content) {
  if (!content) return '暂无内容'
  
  // 清理Markdown格式
  return content
    .replace(/^#+\s*/gm, '') // 移除标题标记
    .replace(/\*\*/g, '') // 移除粗体标记
    .replace(/\*/g, '') // 移除斜体标记
    .replace(/^- /gm, '• ') // 将列表标记转换为圆点
    .replace(/\n\n+/g, '\n\n') // 清理多余空行
    .trim()
}
</script>

<style scoped>
.suggestion-detail {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.detail-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.loading {
  padding: 20px;
}

.detail-content {
  padding: 20px 0;
}

.comment-card {
  margin-bottom: 20px;
}

.comment-content {
  padding: 16px;
}

.rating-info {
  margin-bottom: 12px;
}

.comment-text {
  font-size: 16px;
  line-height: 1.6;
  color: #606266;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.suggestion-card {
  margin-bottom: 20px;
}

.suggestion-content h4 {
  margin: 16px 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.suggestion-text {
  font-size: 16px;
  line-height: 1.6;
  color: #606266;
  margin-bottom: 16px;
}

.reasoning-text {
  font-size: 14px;
  line-height: 1.5;
  color: #909399;
  margin-bottom: 16px;
}

.implementation-steps {
  margin-top: 12px;
}

.implementation-steps ol {
  padding-left: 20px;
}

.implementation-steps li {
  margin-bottom: 8px;
  color: #606266;
}

.analysis-card {
  margin-bottom: 20px;
}

.analysis-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.analysis-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.analysis-item h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.analysis-item p {
  margin: 8px 0;
  color: #606266;
}

.improvement-area {
  margin-bottom: 12px;
}

.area-description {
  margin: 4px 0 0 0;
  font-size: 12px;
  color: #909399;
}

.no-data {
  padding: 40px;
  text-align: center;
}
</style> 